package com.example.administrator.x2picturetransliteration.Home.Activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.administrator.x2picturetransliteration.Base.BaseActivity;
import com.example.administrator.x2picturetransliteration.Base.BasePresenter;
import com.example.administrator.x2picturetransliteration.Home.Dialog.ExportDialog;
import com.example.administrator.x2picturetransliteration.Home.Dialog.PreservationDialog;
import com.example.administrator.x2picturetransliteration.Home.Dialog.SaveDraftDialog;
import com.example.administrator.x2picturetransliteration.Home.Dialog.ShareDialog;
import com.example.administrator.x2picturetransliteration.Home.Presenter.Activity.RecognitionResultsPresenter;
import com.example.administrator.x2picturetransliteration.R;
import com.example.administrator.x2picturetransliteration.RxBus;
import com.example.administrator.x2picturetransliteration.Util.Download.DownloadUtils;
import com.example.administrator.x2picturetransliteration.Util.Download.JsDownloadListener;
import com.example.administrator.x2picturetransliteration.Util.Img.PicassoEqualProportionTransformation2;
import com.example.administrator.x2picturetransliteration.Util.LoadingDialogUtil;
import com.example.administrator.x2picturetransliteration.Util.TimeStampUtil;
import com.example.administrator.x2picturetransliteration.Util.ToastUtil;
import com.example.administrator.x2picturetransliteration.Util.UmengShareUtil;
import com.squareup.picasso.Picasso;
import com.tencent.smtt.sdk.TbsReaderView;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * 识别结果
 * Created by Administrator on 2019/8/20.
 */

public class RecognitionResultsActivity extends BaseActivity implements TbsReaderView.ReaderCallback {

    /** 默认图片识别的时候 只需要传图片地址拼接的字符串*/
    public static void startRecognitionResultsActivity(Context context,String path){

        Intent intent = new Intent(context,RecognitionResultsActivity.class);
        intent.putExtra("path",path);
        context.startActivity(intent);
    }

    /** 表格识别和手写识别的时候，需要传一个type告知类型 */
    public static void startRecognitionResultsActivity(Context context,String path,String type){

        Intent intent = new Intent(context,RecognitionResultsActivity.class);
        intent.putExtra("path",path);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }

    /** 文档列表进入详情的时候，需要传递wordid或者draftid  */
    public static void startRecognitionResultsActivity(Context context,String wordid,String draftid,String type){

        Intent intent = new Intent(context,RecognitionResultsActivity.class);
        intent.putExtra("wordid",wordid);
        intent.putExtra("draftid",draftid);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }

    @BindView(R.id.TitleText)TextView TitleText;
    @BindView(R.id.LButton)ImageView LButton;
    @BindView(R.id.text)TextView text;

    @BindView(R.id.contentEdit)EditText contentEdit;
    @BindView(R.id.webview) WebView webview;
    @BindView(R.id.tbsView) RelativeLayout tbsView;
    @BindView(R.id.contentView)LinearLayout contentView;

    @BindView(R.id.copyView)View copyView; //复制
    @BindView(R.id.translateView)View translateView; //翻译
    @BindView(R.id.jdtsText)TextView jdtsText; //校对可编辑提示

    @BindView(R.id.contentScrollView)View contentScrollView;

    private List<String> paths = new ArrayList<>();

    private String imgs = null; //上传后的图片地址用，号拼接
    private String result = null; //上传后的识别结果
    private String orcResult = null; //上传后的识别结果

    private String wordid = null; //文档id用来判断

    private String draftid = null; //草稿id

    private String toType = "2"; //保存的类型

    private RecognitionResultsPresenter mRecognitionResultsPresenter;

    private TbsReaderView mTbsReaderView;

    @Override
    public int intiLayout() {
        return R.layout.home_activity_recognition_results;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TitleText.setText("识别结果");
        LButton.setImageResource(R.mipmap.home_backw);
        text.setText("保存");

        contentScrollView.setVisibility(View.GONE);

        if (getIntent().getStringExtra("path")!=null) paths.addAll((List<String>) JSON.parse(getIntent().getStringExtra("path")));
        if (getIntent().getStringExtra("wordid")!=null)wordid = getIntent().getStringExtra("wordid");
        if (getIntent().getStringExtra("draftid")!=null)draftid = getIntent().getStringExtra("draftid");

        mRecognitionResultsPresenter = new RecognitionResultsPresenter(this,mCompositeSubscriptions);

        mTbsReaderView = new TbsReaderView(this, this);

        tbsView.addView(mTbsReaderView, new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        if (wordid!=null){

            get(wordid);
            return;

        }else if(draftid!=null){

            get(draftid);
            return;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (paths.size()>0){

            String type = getIntent().getStringExtra("type");

            if ("表格识别".equals(type)){

                toType = "4";

                copyView.setVisibility(View.GONE);
                translateView.setVisibility(View.GONE);
                //jdtsText.setVisibility(View.GONE);
                jdtsText.setText("请导出文档，使用wps或者office软件编辑查看");

                tableParse(0);

            }else if ("文档结构化识别".equals(type)){

                toType = "5";

                copyView.setVisibility(View.GONE);
                translateView.setVisibility(View.GONE);
                //jdtsText.setVisibility(View.GONE);
                jdtsText.setText("请导出文档，使用wps或者office软件编辑查看");

                tableParse(1);

            }else if("手写识别".equals(type)){

                toType = "1";
                handwriting();

            }else {

                toType = "2";
                document();
            }

        }
    }

    /** 保存 */
    @OnClick(R.id.text)
    public void textClick(){
        String type = getIntent().getStringExtra("type");
        if(null==getmap&&TextUtils.isEmpty(result)){
            new ToastUtil(this).getToast(true,"未识别出结果").show();
            return;
        }

        final Map<String,String> map = new HashMap<>();
        String contentEditStr=contentEdit.getText().toString();
        Log.i("leonLog","contentEditStr --> "+contentEditStr);
        map.put("type",toType);
        map.put("imgs",imgs);
        if ("表格识别".equals(type)||"文档结构化识别".equals(type)){
            map.put("result",result);
        }else{
            map.put("result",contentEditStr);
        }
        map.put("orcResult",orcResult);

        if (getmap!=null){
            getmap.put("imgs",imgs);
            getmap.put("result",contentEditStr);
            getmap.put("orcResult",orcResult);
        }

        new PreservationDialog(this, new PreservationDialog.hd() {
            @Override
            public void hdff(String content) {

                map.put("name",content);
                if(getmap!=null)getmap.put("name",content);

                mRecognitionResultsPresenter.addwork(getmap!=null?getmap:map, new BasePresenter.Callback() {
                    @Override
                    public void getData(Object data) {

                        wordid = (String)data;
                        RxBus.getInstance().post(AppActivity.class,"work");
                        RecognitionResultsActivity.this.finish();

                    }
                });
            }

            @Override
            public String nameText() {

                if (getmap==null || getmap.get("name")==null){

                    return "OCR " + new TimeStampUtil().stampToDate(new Date().getTime());

                }else {

                    return getmap.get("name");
                }
            }

        }).show();
    }

    /** 复制 */
    @OnClick(R.id.copyView)
    public void copyViewClick(){
        if(null==getmap&&TextUtils.isEmpty(result)){
            new ToastUtil(this).getToast(true,"未识别出结果").show();
            return;
        }

        if ("".equals(contentEdit.getText() + "")){

                new ToastUtil(this).getToast(false,"没有内容").show();

        }else {

            ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(contentEdit.getText() + "");
            new ToastUtil(this).getToast(false,"复制成功").show();
        }

    }

    /** 分享 */
    @OnClick(R.id.shareView)
    public void shareViewClick(){
        if(null==getmap&&TextUtils.isEmpty(result)){
            new ToastUtil(this).getToast(true,"未识别出结果").show();
            return;
        }

        if (wordid==null){

            new ToastUtil(this).getToast(false,"还没有保存").show();
            return;
        }

        new ShareDialog(this, new ShareDialog.hd() {
            @Override
            public void hdff(final SHARE_MEDIA type, String word) {

                Map<String,String> map = new HashMap<>();
                map.put("id",wordid);
                map.put("exportType",word);

                mRecognitionResultsPresenter.export(map, new BasePresenter.Callback() {
                    @Override
                    public void getData(Object data) {
                        Share(type,data + "");
                    }
                });

            }
        }).show();
    }

    /** 校对 */
    @OnClick(R.id.ProofreadingView)
    public void ProofreadingViewClick(){
        if(null==getmap&&TextUtils.isEmpty(result)){
            new ToastUtil(this).getToast(true,"未识别出结果").show();
            return;
        }

        if (contentView.getVisibility()==View.GONE){

            contentEdit.setEnabled(true);
            contentView.setVisibility(View.VISIBLE);
            contentScrollView.setVisibility(View.VISIBLE);

        }else {

            contentEdit.setEnabled(false);
            contentView.setVisibility(View.GONE);
            contentScrollView.setVisibility(View.GONE);

        }
    }

    /** 导出 */
    @OnClick(R.id.exportView)
    public void exportViewClick(){
        if(null==getmap&&TextUtils.isEmpty(result)){
            new ToastUtil(this).getToast(true,"未识别出结果").show();
            return;
        }


        if (wordid==null){

            new ToastUtil(this).getToast(false,"还没有保存").show();
            return;
        }

        String type = getIntent().getStringExtra("type");

        Boolean judge = null;

        if ("表格识别".equals(type) || "文档结构化识别".equals(type)){

            judge = "表格识别".equals(type)?true:false;
        }

        new ExportDialog(this, judge,new ExportDialog.hd() {
            @Override
            public void hdff(final SHARE_MEDIA type, String word) {

                Map<String,String> map = new HashMap<>();
                map.put("id",wordid);
                map.put("exportType",word);

                mRecognitionResultsPresenter.export(map, new BasePresenter.Callback() {
                    @Override
                    public void getData(Object data) {


                        Share(type,data + "");
                    }
                });

            }

            @Override
            public void hdff2(final boolean qr, String word) {

                Map<String,String> map = new HashMap<>();
                map.put("id",wordid);
                map.put("exportType",word);

                mRecognitionResultsPresenter.export(map, new BasePresenter.Callback() {
                    @Override
                    public void getData(Object data) {

                        Intent intent = new Intent(RecognitionResultsActivity.this,GetQrActivity.class);
                        intent.putExtra("url",data + "");
                        intent.putExtra("title",qr?"生成二维码":"链接");
                        RecognitionResultsActivity.this.startActivity(intent);


                    }
                });
            }
        }).show();
    }

    /** 翻译 */
    @OnClick(R.id.translateView)
    public void translateViewClick(){
        if(null==getmap&&TextUtils.isEmpty(result)){
            new ToastUtil(this).getToast(true,"未识别出结果").show();
            return;
        }

        if(getmap==null){

            TranslateActivity.startTranslateActivity(this,
                    null,null,
                    null,null,
                    wordid,draftid,
                    imgs,contentEdit.getText() + "");

        }else {

            TranslateActivity.startTranslateActivity(this,
                    getmap.get("fromLang"),getmap.get("toLang"),
                    getmap.get("translate"),getmap.get("name"),
                    wordid,draftid,
                    imgs,contentEdit.getText() + "");
        }


    }

    /** 返回 */
    @OnClick(R.id.LButton)
    public void LButtonClick(){

        if (wordid!=null)finish();

        new SaveDraftDialog(this, new SaveDraftDialog.hd() {
            @Override
            public void ok() {

                bccgx();
                finish();
            }

            @Override
            public void no() {

                finish();
            }
        }).show();

    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();

        if (wordid!=null)finish();

        new SaveDraftDialog(this, new SaveDraftDialog.hd() {
            @Override
            public void ok() {

                bccgx();
                finish();
            }

            @Override
            public void no() {

                finish();
            }
        }).show();
    }

    /** 上传图片识别 */
    private void document(){

        mRecognitionResultsPresenter.document(paths, new BasePresenter.Callback() {
            @Override
            public void getData(Object data) {

                Map<String,String> map = (Map<String,String>)data;

                imgs = map.get("imgs");
                result = map.get("result");

                List<String> img = Arrays.asList(map.get("imgs").split(","));

                contentEdit.setText(map.get("result"));

                for (String path:img){

                    ImageView imageView = new ImageView(RecognitionResultsActivity.this);

                    Picasso.with(RecognitionResultsActivity.this)
                            .load(path)
                            .placeholder(R.drawable.home_advertisement)
                            .transform(new PicassoEqualProportionTransformation2(imageView))
                            .error(R.drawable.home_advertisement)
                            .into(imageView);

                    contentView.addView(imageView);

                }

            }
        });
    }

    /** 表格识别 */
    private void tableParse(int ocr){

        mRecognitionResultsPresenter.tableParse(ocr,paths.get(0), new BasePresenter.Callback() {
            @Override
            public void getData(Object data) {

                Map<String,String> map = (Map<String,String>)data;

                imgs = map.get("imgs");
                result = map.get("result");
                orcResult = map.get("orcResult");

                List<String> img = Arrays.asList(map.get("imgs").split(","));

                setweb(map.get("result"));

                for (String path:img){

                    ImageView imageView = new ImageView(RecognitionResultsActivity.this);

                    Picasso.with(RecognitionResultsActivity.this)
                            .load(path)
                            .placeholder(R.drawable.home_advertisement)
                            .transform(new PicassoEqualProportionTransformation2(imageView))
                            .error(R.drawable.home_advertisement)
                            .into(imageView);

                     contentView.addView(imageView);

                }

                String a = "";
            }
        });
    }

    /** 手写识别 */
    private void handwriting(){

        mRecognitionResultsPresenter.handwriting(paths.get(0), new BasePresenter.Callback() {
            @Override
            public void getData(Object data) {

                Map<String,String> map = (Map<String,String>)data;

                imgs = map.get("imgs");
                result = map.get("result");

                List<String> img = Arrays.asList(map.get("imgs").split(","));

                contentEdit.setText(map.get("result"));

                for (String path:img){

                    ImageView imageView = new ImageView(RecognitionResultsActivity.this);

                    Picasso.with(RecognitionResultsActivity.this)
                            .load(path)
                            .placeholder(R.drawable.home_advertisement)
                            .transform(new PicassoEqualProportionTransformation2(imageView))
                            .error(R.drawable.home_advertisement)
                            .into(imageView);

                    contentView.addView(imageView);

                }

            }
        });
    }

    /** 详情 */
    private Map<String,String> getmap = null; //详情请求来的数据，用来保存或者保存草稿
    private void get(String id){

        mRecognitionResultsPresenter.get(id, new BasePresenter.Callback() {
            @Override
            public void getData(Object data) {

                getmap = (Map<String,String>)JSON.parse(data + "");


                imgs = getmap.get("imgs");
                result = getmap.get("result");
                orcResult = getmap.get("orcResult");

                List<String> img = Arrays.asList(getmap.get("imgs").split(","));

                String resultdata = getmap.get("result").toString();



                if(resultdata!=null && resultdata.indexOf("<html>")!=-1){

                    //setweb(getmap.get("result"));
                    setweb(getmap.get("result"));
                    copyView.setVisibility(View.GONE);
                    translateView.setVisibility(View.GONE);
                    //jdtsText.setVisibility(View.GONE);
                    jdtsText.setText("请导出文档，使用wps或者office软件编辑查看");


                }else {

                    contentEdit.setText(getmap.get("result"));
                }


                for (String path:img){

                    ImageView imageView = new ImageView(RecognitionResultsActivity.this);

                    Picasso.with(RecognitionResultsActivity.this)
                            .load(path)
                            .placeholder(R.drawable.home_advertisement)
                            .transform(new PicassoEqualProportionTransformation2(imageView))
                            .error(R.drawable.home_advertisement)
                            .into(imageView);

                    contentView.addView(imageView);

                }
            }
        });

    }

    private void Share(SHARE_MEDIA mSHARE_MEDIA,String url){

        UmengShareUtil mUmengShareUtil = new UmengShareUtil(this);
        mUmengShareUtil.setUrl(url);
        mUmengShareUtil.setTitle("识别结果");
        mUmengShareUtil.setThumb(R.mipmap.home_logo);
        mUmengShareUtil.setDescription("表格识别识别结果");
        mUmengShareUtil.Share(mSHARE_MEDIA);
    }

    /** 没有wordid的情况下保存到草稿箱 */
    @Override
    protected void onDestroy() {

        super.onDestroy();
        mTbsReaderView.onStop();
    }

    private void bccgx(){

        Map<String,String> map = new HashMap<>();

        if (draftid!=null)map.put("id",draftid);
        map.put("type",toType);
        map.put("name","CG " + new TimeStampUtil().stampToDate(new Date().getTime()));
        map.put("imgs",imgs);

        if("".equals(contentEdit.getText()+"")){

            map.put("result",result);

        }else {

            map.put("result",contentEdit.getText() + "");
        }

        map.put("orcResult",orcResult);

        if (getmap!=null){

            if("".equals(contentEdit.getText()+"")){

                map.put("result",result);

            }else {

                map.put("result",contentEdit.getText() + "");
            }
        }

        if (wordid==null) {

            RxBus.getInstance().post(AppActivity.class, JSON.toJSONString(getmap!=null?getmap:map));
        }

    }

    private void setweb(String html){

        //Download(html);

        webview.loadDataWithBaseURL(null, "<head><style>img{max-width:100% !important;}</style></head>" + html, "text/html", "UTF-8", null);

        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

        
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                view.loadUrl(url);//此行代码必须添加上去，否则不会显示
                return false;// 在跳转链接时强制在当前webview中加载
            }
        });
    }

    @Override
    public void onCallBackAction(Integer integer, Object o, Object o1) {

    }

    private String getFileType(String paramString) {
        String str = "";

        if (TextUtils.isEmpty(paramString)) {
            Log.d("print", "paramString---->null");
            return str;
        }
        Log.d("print", "paramString:" + paramString);
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {
            Log.d("print", "i <= -1");
            return str;
        }

        str = paramString.substring(i + 1);
        Log.d("print", "paramString.substring(i + 1)------>" + str);
        return str;
    }

    /**
     * 下载
     * */
    public void Download(final String url){

        List<String> urls = Arrays.asList(url.split("//"));
        if (urls==null || urls.size()!=2)return;

        List<String> path = Arrays.asList(urls.get(1).split("/"));
        if (path==null || path.size()<2)return;

        String head = urls.get(0) + "//" + path.get(0) + "/";

        final String fileName = path.get(path.size()-1);

        String Route = "";

        for (int j=1;j<path.size()-1;j++){

            Route = Route + path.get(j) + "/";
        }

        final String SD = getSDPath();
        if (SD==null)return;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                LoadingDialogUtil.getInstance(RecognitionResultsActivity.this).show();
            }
        });

        new DownloadUtils(head, new JsDownloadListener() {
            @Override
            public void onStartDownload() {

            }

            @Override
            public void onProgress(final int progress) {


                if (progress>=100){

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            LoadingDialogUtil.getInstance(RecognitionResultsActivity.this).dismiss();
                        }
                    });

                    final Bundle bundle = new Bundle();
                    bundle.putString("filePath", SD + "/" + fileName);
                    bundle.putString("tempPath", Environment.getExternalStorageDirectory() + "/TbsReaderTemp");

                    boolean result = mTbsReaderView.preOpen(getFileType(SD + "/"+ fileName), false);
                    if (result) {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                mTbsReaderView.openFile(bundle);
                            }
                        });

                    }else{

                    }
                }

            }

            @Override
            public void onFinishDownload() {

            }

            @Override
            public void onFail(String errorInfo) {

            }

        }).download(Route + fileName, SD + "/" + fileName, new Subscriber() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Object o) {

            }
        });
    }

    public String getSDPath() {
        File sdDir = null;
        //判断sd卡是否存在
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取根目录
            Log.e("qq", "外部存储可用..." + sdDir.toString());
        }
        return sdDir!=null?sdDir.toString():null;
    }
}
